import React, { useCallback, useEffect, useState } from "react";
import { useHistory, useLocation } from "umi";
import Icon from "../Icon";
import classnames from "classnames";
import "./index.less";

declare interface MenuItem {
  key: string;
  path: string;
  name: string;
  icon: string;
}

const menuList: MenuItem[] = [
  {
    key: "applications",
    path: "/applications",
    name: "应用",
    icon: "iconrobot",
  },
  {
    key: "history",
    path: "/history",
    name: "历史",
    icon: "iconlishi",
  },
  {
    key: "log",
    path: "/log",
    name: "日志",
    icon: "iconrizhi",
  },
];

const MenuItem: React.FC<MenuItem & { activeKey: string | undefined }> = (props) => {
  const history = useHistory();
  const onClick = useCallback(() => {
    history.replace(props.path);
  }, [props, history]);
  return (
    <div onClick={onClick}
         className={classnames("menu-item", {"active": props.path.includes(props.activeKey || "@@")})}>
      <Icon name={props.icon}
            className={classnames("menu-part", "menu-icon")}/>
      <span className={classnames("menu-part", "menu-text")}>{props.name}</span>
    </div>
  );
};

const Menu: React.FC = () => {
  const [activeKey, setActiveKey] = useState<string | undefined>();
  const location = useLocation();

  useEffect(() => {
    const {pathname} = location;
    const [key] = pathname.split("/").filter(t => !!t);
    setActiveKey(key);
  }, [location.pathname]);

  return (
    <div className='menu'>
      {menuList.map(item => (
        <MenuItem {...item} activeKey={activeKey}/>
      ))}
    </div>
  );
};

export default Menu;
